<?php
namespace app\common\job;

use app\common\model\CommonModel;
use Exception;
use think\facade\Log;
use think\queue\Job;

class ModelJob
{
    /**
     * 修改数据字段
     * @author 贺强
     * @time   2023/9/2 20:44
     * @param Job   $job  当前任务
     * @param array $data 要修改的数据，必须包含数据主键 ID
     * @return bool
     */
    public function modify_field(Job $job, array $data)
    {
        if (empty($data)) {
            $job->delete();
            return false;
        }
        try {
            $table = $data['table'];
            CommonModel::$tablename = $table;
            $where = $data['where'] ?? '';
            $res = CommonModel::modify($data['data'], $where);
            if ($res) {
                $job->delete();
                return true;
            } elseif ($job->attempts() > 10) {
                $job->delete();
                $error = ['jobName' => $job->getName(), 'data' => $data];
                throw new Exception('执行次数超限:' . json_encode($error));
            } else {
                $job->release();
                return false;
            }
        } catch (Exception $e) {
            $job->delete();
            Log::error($e->getMessage());
            return false;
        }
    }
}
